package com.mfl.service.impl;


import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.mfl.common.PageResult;
import com.mfl.constant.MessageConstant;
import com.mfl.context.BaseContext;
import com.mfl.exception.*;
import com.mfl.mapper.AdminMapper;
import com.mfl.mapper.PostMapper;
import com.mfl.mapper.PostRemarkMapper;
import com.mfl.pojo.dto.AdminDTO;
import com.mfl.pojo.dto.AdminLoginDTO;
import com.mfl.pojo.dto.AdminPageQueryDTO;
import com.mfl.pojo.entity.Admin;
import com.mfl.pojo.vo.AdminPageQueryVO;
import com.mfl.pojo.vo.AdminVO;
import com.mfl.properties.AESProperties;
import com.mfl.service.AdminService;
import com.mfl.service.PostService;
import com.mfl.utils.AESUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private AESProperties aesProperties;
    @Autowired
    private PostMapper postMapper;
    @Autowired
    private PostRemarkMapper postRemarkMapper;

    /**
     * s
     * 管理员登录
     *
     * @param adminLoginDTO
     * @return
     */
    @Override
    public Admin login(AdminLoginDTO adminLoginDTO) {
        String username = adminLoginDTO.getUsername();
        String password = adminLoginDTO.getPassword();

        // 判断管理员账号是否存在
        Admin admin = adminMapper.selectByUname(username);
        if (admin == null) {
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        if (admin.getStatus() == 0) {
            throw new AccountNotAvailable(MessageConstant.ACCOUNT_NOT_AVAILABLE);
        }
        // 密码进行md5加密
        try {
            password = AESUtil.encrypt(password, aesProperties.getSecretKey());
        } catch (Exception e) {
            throw new ServerErrorException(MessageConstant.SERVER_ERROR);
        }
        if (!password.equals(admin.getAdminPwd())) {
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        return admin;
    }

    /**
     * 新增管理员
     *
     * @param adminDTO
     */
    @Override
    public void insert(AdminDTO adminDTO) {
        // 先判断管理员账号是否存在
        Admin admin = adminMapper.selectByUname(adminDTO.getAdminUname());
        if (admin != null) {
            throw new AccountAlreadyExistsException(MessageConstant.ACCOUNT_ALREADY_EXISTS);
        }
        // 密码进行md5加密
        String password = null;
        try {
            password = AESUtil.encrypt(adminDTO.getAdminPwd(), aesProperties.getSecretKey());
        } catch (Exception e) {
            throw new ServerErrorException(MessageConstant.SERVER_ERROR);
        }
        // 开始反射异常，在实体类中加上了无参和全参构造
        Admin newAdmin = Admin.builder()
                .adminUname(adminDTO.getAdminUname())
                .adminPwd(password)
                .name(adminDTO.getName())
                .gender(adminDTO.getGender())
                .phone(adminDTO.getPhone())
                .status(adminDTO.getStatus())
                .createUser(BaseContext.getCurrentId())
                .createTime(LocalDateTime.now())
                .build();
        adminMapper.insert(newAdmin);
    }

    /**
     * 分页查询管理员信息
     *
     * @param adminPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(AdminPageQueryDTO adminPageQueryDTO) {
        // 开启分页查询
        PageHelper.startPage(adminPageQueryDTO.getPage(), adminPageQueryDTO.getPageSize());
        Page<AdminPageQueryVO> page = adminMapper.queryByPage(adminPageQueryDTO);
        page.getResult().forEach(item -> {
            // 密码AES解密
            try {
                String pwd = AESUtil.decrypt(item.getAdminPwd(), aesProperties.getSecretKey());
                item.setAdminPwd(pwd);
            } catch (Exception e) {
                throw new ServerErrorException(MessageConstant.SERVER_ERROR);
            }
        });
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 批量删除管理员信息
     *
     * @param ids
     */
    @Override
    public void batchDelete(List<Integer> ids) {
        adminMapper.deleteByIds(ids);
        // 删除用户之后，需要将用户关联的帖子删除
        // 先查到对应帖子的id后删除帖子的回复
        List<Integer> list = postMapper.getIdByCreateUser(ids);
        if (!list.isEmpty()) {
            // 删除帖子回复
            postRemarkMapper.deleteByPostIds(list);
            // 删除帖子
            postMapper.deleteByUserIds(ids);
        }
    }

    /**
     * 修改管理员状态
     *
     * @param id
     * @param status
     */
    @Override
    public void updateStatus(Integer status, Integer id) {
        adminMapper.updateStatusById(status, id);
    }

    /**
     * 根据id查询管理员信息
     *
     * @param id
     * @return
     */
    @Override
    public AdminVO getByAdminId(int id) {
        Admin admin = adminMapper.getByAdminId(id);
        String password = null;
        try {
            password = AESUtil.decrypt(admin.getAdminPwd(), aesProperties.getSecretKey());
        } catch (Exception e) {
            throw new ServerErrorException(MessageConstant.SERVER_ERROR);
        }
        AdminVO vo = AdminVO.builder()
                .id(admin.getId())
                .adminUname(admin.getAdminUname())
                .adminPwd(password)
                .name(admin.getName())
                .phone(admin.getPhone())
                .gender(admin.getGender())
                .status(admin.getStatus())
                .build();
        return vo;
    }

    /**
     * 修改管理员信息
     *
     * @param adminDTO
     */
    @Override
    public void update(AdminDTO adminDTO) {
        String password = null;
        try {
            password = AESUtil.encrypt(adminDTO.getAdminPwd(), aesProperties.getSecretKey());
        } catch (Exception e) {
            throw new ServerErrorException(MessageConstant.SERVER_ERROR);
        }
        Admin admin = Admin.builder()
                .id(adminDTO.getId())
                .adminUname(adminDTO.getAdminUname())
                .adminPwd(password)
                .name(adminDTO.getName())
                .phone(adminDTO.getPhone())
                .gender(adminDTO.getGender())
                .status(adminDTO.getStatus())
                .updateUser(BaseContext.getCurrentId())
                .updateTime(LocalDateTime.now())
                .build();
        adminMapper.update(admin);
    }
}
